#include "../src/proxy.h"
#include "event_bus.hpp"
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <chrono>
#include <thread>

// static_assert(sizeof(CEvent) == 132, "CEvent size mismatch!");

extern "C" {
    void eb_push(const CEvent* e) { 
        // 直接使用CEvent的数据创建Event对象并推送
        // 注意：这里不再复制payload，而是直接使用指针
        Event event(e->id, e->payload, e->payload_size);
        EventBus::instance().push(event); 
    }

    int  eb_pop(CEvent* e) { 
        // 创建Event对象接收数据
        Event event(0, nullptr, 0);
        bool result = EventBus::instance().pop(event);
        if (result) {
            // 将数据复制到CEvent结构
            e->id = event.id;
            e->payload_size = event.payload_size;
            // 只有当payload_size大于0时才分配内存
            if (event.payload_size > 0 && event.payload) {
                e->payload = (char*)malloc(event.payload_size);
                if (e->payload) {
                    memcpy(e->payload, event.payload, event.payload_size);
                } else {
                    e->payload = nullptr;
                    e->payload_size = 0;
                }
            } else {
                e->payload = nullptr;
                e->payload_size = 0;
            }
        }
        return result; 
    }
    
    // 创建CEvent对象
    CEvent* eb_create_event(int id, const char* payload, size_t size) {
        CEvent* e = (CEvent*)malloc(sizeof(CEvent));
        if (e) {
            e->id = id;
            e->payload_size = size;
            // 只有当size大于0时才分配内存
            if (size > 0 && payload) {
                e->payload = (char*)malloc(size);
                if (e->payload) {
                    memcpy(e->payload, payload, size);
                } else {
                    e->payload = nullptr;
                    e->payload_size = 0;
                }
            } else {
                e->payload = nullptr;
                e->payload_size = 0;
            }
        }
        return e;
    }
    
    // 销毁CEvent对象
    void eb_destroy_event(CEvent* e) {
        if (e) {
            if (e->payload) {
                free(e->payload);
                e->payload = nullptr;
            }
            free(e);
        }
    }
    
    // 释放payload内存
    void eb_free_payload(char* payload) {
        if (payload) {
            free(payload);
        }
    }
    
    // 恢复start函数
    void start() {
        auto& b = EventBus::instance();
        Event e1{ 1, "hello",6 };
        b.push(e1);
        while (true) {
            static int id = 3;
            Event e3{ id, "hello",6 };
            b.push(e3);
            id++;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
}